package top.h1234.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import top.h1234.mapper.UserMapper;
import top.h1234.pojo.User;
import top.h1234.util.SqlSessionFactoryUtils;

public class UserService {
    // 1. 获取工厂对象
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public User login(String username, String password) {
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 4. 执行sql
        User user = mapper.select(username, password);
        // 5. 释放资源
        sqlSession.close();
        // 6. 返回数据
        return user;
    }

    public boolean register(User user) {
        // 2. 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3. 获取mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 4. 执行sql
        User username = mapper.selectByUsername(user.getUsername());
        // 判断
        if (username == null) {
            // 用户不存在，可以注册
            mapper.add(user);
            sqlSession.commit();
        }
        // 5. 释放资源
        sqlSession.close();
        // 6. 返回数据
        return username == null;
    }
}
